package com.xxl.job.admin.core.util;

import com.alibaba.fastjson.JSONArray;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.URISyntaxException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UseAPI {
    public static PreparedStatement conn(String sql) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 定义mysql连接地址、用户名、密码
        String url = "jdbc:mysql://192.168.0.100:3306/job0930?characterEncoding=utf-8&serverTimezone=GMT";
        String username = "root";
        String password = "123456";
        // 获取数据库连接
        Connection connection = DriverManager.getConnection(url, username, password);
        // 获取一个预处理sql对象
        PreparedStatement statement = connection.prepareStatement(sql);
        return statement;
    }


    static void getPrometheusAPI(String parm) {
        String paramValue = "http_requests_total";
//HTTP客户端连接工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //参数里有特殊字符，不能直接写成String（会报Illegal Character错误），用URIBuilder构造。
        URIBuilder uri = null;
        HttpGet get = null;
        try {
            //一对参数，使用addParameter(param: ,value:)这个方法添加参数。
            //若多对参数，使用第二种方法（但其实在这里没有这种情况）：uri.addParameters(List<NameValuePair>);
            //这里的ip，port换成你的Prometheus的ip+port。paramValue要自己定义，比如http_request_total
            uri = new URIBuilder("http://oy-d2000:9090/api/v1/query");
            //uri.addParameter("query","(sum(increase(node_cpu_seconds_total{mode=\"idle\"}[1m]))by(instance))/(sum(increase(node_cpu_seconds_total[1m]))by(instance))");
            //uri.addParameter("query","node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes");//uri此时是http://ip:port/api/v1/query?query=http_requests_total
            uri.addParameter("query",parm);
            System.out.println(uri);
            get = new HttpGet(uri.build());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = null;
        CloseableHttpResponse response = null;
        try {
            // 执行请求并接收+转换  得到jsonObject就可以解析了。
            response = httpClient.execute(get);
            String resStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            jsonObject = JSONObject.parseObject(resStr);
            jsonObject.get("status");
            //得到的是JSONObject
            jsonObject.getJSONObject("data");
            //提取出JSONArray

            JSONArray result= jsonObject.getJSONObject("data").getJSONArray("result");
            //数组元素的获取用索引index
            for(int i=0;i<result.size();i++){
                //时间序列由一组标签确定，这里取指标名"__name__"和实例名"instance"打印
                JSONObject metric = result.getJSONObject(i).getJSONObject("metric");
                System.out.println("\nMetric_Name:"+metric.get("__name__")+"  Instance:"+metric.get("instance"));
                //时间戳+样本值   其中时间戳可以用别的数据类型取（考虑存储方式？）  以上这些数据都可以用Map保存
                JSONArray value = result.getJSONObject(i).getJSONArray("value");
                System.out.println("timestamp:"+value.getString(0)+"  requestTotal:"+value.getString(1));
            }


        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getJobInfoSource(String value) throws SQLException, ClassNotFoundException {
        //XxlJobInfo jobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(id);
        //String sql = "select * from xxl_job_info where id=?";
        String sql = "select * from xxl_job_info";
        PreparedStatement statement = conn(sql);
        //statement.setString(1,id);
        ResultSet rs = statement.executeQuery();
//        if(rs != null&& rs.next()){
        while(rs.next()){
            String jobid = rs.getString("id");
            String sourceType = rs.getString(value);
            System.out.println(jobid+":"+sourceType);
        }

    }
    public static void getJobGroupSource(String value) throws SQLException, ClassNotFoundException {
        //XxlJobInfo jobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(id);
        //String sql = "select * from xxl_job_info where id=?";
        String sql = "select * from xxl_job_group";
        PreparedStatement statement = conn(sql);
        //statement.setString(1,id);
        ResultSet rs = statement.executeQuery();
//        if(rs != null&& rs.next()){
        while(rs.next()){
            String jobid = rs.getString("app_name");
            int sourceType = rs.getInt(value);
            System.out.println(jobid+":"+sourceType);
        }

    }
    public static int getNewLog(int value) throws SQLException, ClassNotFoundException {
        //XxlJobInfo jobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(id);
        //String sql = "select * from xxl_job_info where id=?";
        String sql = "select * from xxl_job_log where job_id="+value+" order by trigger_time desc limit 0,1 ";
        PreparedStatement statement = conn(sql);
        //statement.setString(1,id);
        ResultSet rs = statement.executeQuery();
//        if(rs != null&& rs.next()){
        String id = "";
        while(rs.next()){
            id = rs.getString("id");
            //int sourceType = rs.getInt(value);
            //System.out.println("最新"+id);
        }
        if(id=="")return -1;
        return Integer.parseInt(id);

    }
    public static int getFreeJob(int id) throws SQLException, ClassNotFoundException {
        //XxlJobInfo jobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(id);
        //String sql = "select * from xxl_job_info where id=?";
        String sid =String.valueOf(id);
        String sql = "select * from xxl_job_log where job_id = "+sid+" and handle_code = 0";
        PreparedStatement statement = conn(sql);
        //statement.setString(1,id);
        ResultSet rs = statement.executeQuery();
        int flag =0;

            while (rs.next()) {
                String jobid = rs.getString("id");
                String handle_code = rs.getString("handle_code");
                flag = 1;
                 System.out.println(jobid+":"+handle_code);


            }
        //System.out.println("flag"+flag);
        if(flag == 1) return 1;
        return 0;


    }

    public static ArrayList<Integer> getParentJob(int id) throws SQLException, ClassNotFoundException {
        //XxlJobInfo jobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(id);
        //String sql = "select * from xxl_job_info where id=?";
        ArrayList<Integer> ParentId = new ArrayList<>();
        String sql = "select * from xxl_job_info where child_jobid like \"%"+id+"%\"";
        PreparedStatement statement = conn(sql);
        //statement.setString(1,id);
        ResultSet rs = statement.executeQuery();
//        if(rs != null&& rs.next()){
        while(rs.next()){
            String jobid = rs.getString("id");
            ParentId.add(Integer.parseInt(jobid));
            System.out.println(jobid);
        }
        return ParentId;

    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException, InterruptedException {
//        System.out.println("查询cpu空闲率：");
//        getPrometheusAPI("(sum(increase(node_cpu_seconds_total{mode=\"idle\"}[1m]))by(instance))/(sum(increase(node_cpu_seconds_total[1m]))by(instance))");
//        System.out.println("查询内存空闲率：");
//        getPrometheusAPI("node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes");
//
//        System.out.println("查询任务硬件资源：");
//        getJobInfoSource("source_type");
//
//        System.out.println("查询可用计算资源资源：");
//        getJobGroupSource("GPU");

        //getFreeJob("105");
        System.out.println(getNewLog(125));
//        System.out.println(getParentJob(127));
//        while(getFreeJob(129)==1){
//            System.out.println("执行中");
//           Thread.sleep(5000);
//        }
//       System.out.println("已释放");
    }


}
